package com.amehta.proxy.redis;

import io.dropwizard.lifecycle.Managed;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.JedisPool;

public class JedisPoolManager implements Managed {

    private static Logger LOGGER = LoggerFactory.getLogger(JedisPoolManager.class);

    private String redisAddress;
    private int redisTimeout;
    private String redisPassword;
    private int redisDataBase;
    private int redisPort;
    private int jedisPoolSize;
    private JedisPool jedisPool;


    public JedisPoolManager(String redisAddress, int redisTimeout, String redisPassword, int redisDataBase, int redisPort, int jedisPoolSize) {
        this.redisAddress = redisAddress;
        this.redisTimeout = redisTimeout;
        this.redisPassword = redisPassword;
        this.redisDataBase = redisDataBase;
        this.redisPort = redisPort;
        this.jedisPoolSize = jedisPoolSize;
    }

    public JedisPoolManager(String redisAddress, int redisPort, int jedisPoolSize) {
        this.redisAddress = redisAddress;
        this.redisPort = redisPort;
        this.jedisPoolSize = jedisPoolSize;
    }

    @Override
    public void start() {
        LOGGER.info("starting...");
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMaxTotal(this.jedisPoolSize);
        // this.jedisPool = new JedisPool(config, this.redisAddress, this.redisPort);
        this.jedisPool = new JedisPool(config, this.redisAddress, this.redisPort, this.redisTimeout, this.redisPassword, this.redisDataBase);
        LOGGER.info("started");
    }

    @Override
    public void stop() {
        LOGGER.info("shutting down");
        this.jedisPool.close();
        LOGGER.info("shut down");
    }

    public JedisPool getJedisPool() {
        return this.jedisPool;
    }
}
